//
//  CutFruitLayer.cpp
//  SchoolLunchFood
//
//  Created by luotianqiang1 on 16/10/27.
//
//

#include "CutFruitLayer.h"
#include "FoodData.h"
#include "FrameStatus.h"
#include "CutComponent.h"
#include "particleLayer.h"
#include "MakeIce.h"
IMPLEMENT_COCOS2DX_CLASS(CutFruitLayer);
REGIST_SECENE(CutFruitLayer)
bool CutFruitLayer::init(){
    if(BaseStepLayer::init()) {
        autoShowBtnName.clear();
        fruitlayer  = nullptr;
        _operate = StudioLayer::create("ChooseFruit.csb");
        this->addChild(_operate,1);
        cutPaths = FoodData::getCutPath();
        if(cutPaths.size()>0){
            createFood(cutPaths.at(0));
            auto bowl = _operate->getNodeByName("bowl");
            auto fruit = StudioLayer::createNoLayout("cutLayer/"+FoodData::getFlavor()+".csb");
            auto fruitBow = fruit->getNodeByName("bowl");
            Vector<Node*> newChilds(fruitBow->getChildren());
            for(auto node:newChilds){
                node->removeFromParent();
                bowl->addChild(node);
                node->setVisible(node->getName() == "bowlUp");
            }
            bowl->setVisible(false);
        }
        
        
        return true;
    }
    return false;
}

void CutFruitLayer::touchEnd(ui::Widget* widget){
    
}

void CutFruitLayer::createFood(const string& csbPath){
    Vec2 knifePos = Vec2::ZERO;
    Vec2 innerPos = Vec2::ZERO;
    if(fruitlayer != nullptr){
        auto knife = fruitlayer->getNodeByName("knife");
        if(knife){
            knifePos = knife->getPosition();
            innerPos = knife->getChildByName("inner")->getPosition();
        }
          fruitlayer->removeFromParent();
    }
    foods.clear();
    fruitlayer = StudioLayer::create(csbPath);
    _operate->getNodeByName("optionLayer")->addChild(fruitlayer);
    
    auto knife = fruitlayer->getNodeByName("knife");
    if(knifePos != Vec2::ZERO) {
        knife->setPosition(knifePos);
        knife->getChildByName("inner")->setPosition(innerPos);
    }else {
        knife->setVisible(false);
    }
    for(int i=0;i<50;i++){
        auto food = fruitlayer->getNodeByName(StringUtils::format("food%d",i));
        if(food != nullptr){
            food->setVisible(false);
            foods.push_back(food);
        }
        else
            break;
    }
    auto num = foods.size();
    for(int i=0;i<num;i++){
        auto food = foods.at(i);
        if(knife->getScaleX()<0){
            food->getParent()->reorderChild(food, num-i);
        }else {
            food->getParent()->reorderChild(food, i);
        }
        
    }
    knife->getParent()->reorderChild(knife, num+1);
    _prompt = fruitlayer->getNodeByName<Sprite*>("finger");
    
}

void CutFruitLayer::show(){
    if(fruitlayer == nullptr)
        return ;
    _eventDispatcher->setEnabled(false);
    SoundPlayer::getInstance()->playEffect("sound/general/ingredients_fly_in.mp3");
    for(auto food:foods){
        ActionHelper::showBezier(food, food->getPosition(), ActionHelper::ShowDirection::show_from_left);
        food->setVisible(true);
    }
    ActionHelper::delayFunc(0.5, this, [this](){
        _eventDispatcher->setEnabled(true);
        auto knife = fruitlayer->getNodeByName("knife");
        vector<Vec2> cutPos;
        auto f = FrameStatus::create(knife->getName());
        f->setSearchAction(fruitlayer->getAction());
        for(int i=0;i<(foods.size()-1)*2;i++){
            cutPos.push_back(f->searchPostion(StringUtils::format("cut%d",i)));
        }
        
        auto endFunc = [=](){
            cutLines.clear();
            for(int i=0;i<cutPos.size();i=i+2){
                auto line = Sprite::create("ui/line1.png");
                if(knife->getScaleX()<0){
                    line->setFlippedX(true);
                    line->setPosition(knife->getParent()->convertToWorldSpace((cutPos[i]+cutPos[i+1])*.5)+Vec2(37,17));
                }else {
                    line->setPosition(knife->getParent()->convertToWorldSpace((cutPos[i]+cutPos[i+1])*.5)-Vec2(30,0));
                }
                this->addChild(line,10);
                cutLines.push_back(line);
            }
            auto cut = CutComponent::create();
            cut->addListners(CutComponent::cut_count, [=](LQComponent*,OperateListner* lis){
                auto index = dynAny_cast<int>(lis->getData());
                if(index-1<cutLines.size())
                    cutLines.at(index-1)->removeFromParent();
                ActionHelper::delayFunc(0.2f, knife, [=](){
                    if(knife->getScaleX()<0&&index<foods.size()){
                        knife->getParent()->reorderChild(knife, foods[index]->getLocalZOrder()-1);
                    } else {
                        knife->getParent()->reorderChild(knife, index);
                    }
                });
                
                if(index != foods.size()-1){
                    auto food = fruitlayer->getNodeByName(StringUtils::format("food%d",index-1));
                    food->runAction(EaseExponentialOut::create(MoveBy::create(0.2, Vec2(20*(foods.size()-1-index),0))));
                }else {
                    auto food = fruitlayer->getNodeByName(StringUtils::format("food%lu",foods.size()-1));
                    food->runAction(EaseExponentialOut::create(MoveBy::create(0.2, Vec2(-20,0))));
                }
                
            });
            cut->addListners(CutComponent::cut_end, [=](LQComponent*,OperateListner* lis){
                knife->stopAllActions();
                knife->getParent()->reorderChild(knife, foods.size()+1);
                addParicle(fruitlayer->getPosinWord("board"));
                  ActionHelper::hide(knife, ActionHelper::ShowDirection::show_from_right);
                ActionHelper::delayFunc(0.5, this, [=](){
                    int index = FoodData::getCutPath().size()-cutPaths.size();
                  
                    ActionHelper::runBezierMoveHideAction(_prompt, _operate->getPosinWord("board"), _operate->getPosinWord("bowl"));
                    for(int i=0;i<foods.size();i++){
                        auto f = foods.at(i);
                        auto move = TouchMoveComponent::create();
                        move->setTarget(LQRect::create(CocosHelper::getNodeRectInWorld(_operate->getNodeByName("bowl"))));
                        f->addComponent(move);
                        move->setSwallowTouches(false);
                        move->setBrintTop(false);
                        move->setMoveType(MoveComponentType::kTypeBack);
                        move->addListners(ComponentTouchEnd, [=](LQComponent*,OperateListner*){
                            this->stopPrompt();
                            float delayTime = 0.13*i;
                            auto finBowl = _operate->getNodeByName(StringUtils::format("food%d%d",index,i));
                            f->runAction(Sequence::create(DelayTime::create(delayTime), JumpTo::create(0.6f, f->getParent()->convertToNodeSpace(finBowl->convertToWorldSpace(finBowl->getContentSize()*.5)), 200, 1),nullptr));
                            f->runAction(Sequence::create(DelayTime::create(delayTime), ScaleTo::create(0.6f, finBowl->getScaleX()),nullptr));
                            f->runAction(Sequence::create(DelayTime::create(delayTime),CallFunc::create([](){
                                SoundPlayer::getInstance()->playEffect("sound/general/ingredients_fly_in.mp3");
                            }), RotateTo::create(0.6f, finBowl->getRotationX()),CallFunc::create([=](){
                                f->removeFromParent();
                                finBowl->setVisible(true);
                                if(i == foods.size() -1){
                                    cutPaths.erase(cutPaths.begin());
                                    if(cutPaths.size() == 0){
                                        ActionHelper::hide(fruitlayer->getNodeByName("board"), ActionHelper::ShowDirection::show_from_left,CC_CALLBACK_0(CutFruitLayer::cutAllEnd,this));
                                    }else {
                                        createFood(*cutPaths.begin());
                                        show();
                                    }
                                }
                            }), nullptr));
                        });
                    }
                    
                    
                    
                    
                });
            });
            cut->setTarget(LQRect::create(CocosHelper::getNodeRectInWorld(fruitlayer->getNodeByName("board"))));
            
            cut->setCutPoints(cutPos);
            knife->addComponent(cut);
            if(knife->getScaleX()<0){
                knife->getParent()->reorderChild(knife,foods[0]->getLocalZOrder()-1);
            }else {
                knife->getParent()->reorderChild(knife,0);
            }
            
        };
        auto inner = knife->getChildByName("inner");
        inner->stopAllActions();
        inner->runAction(MoveTo::create(0.2, inner->getContentSize()*.5));
        if(!knife->isVisible()){
            
            SoundPlayer::getInstance()->playEffect("sound/general/ingredients_fly_in.mp3");
            ActionHelper::showBezier(knife, knife->getPosition(), ActionHelper::ShowDirection::show_from_right,endFunc);
        }
        else{
            knife->runAction(Sequence::create(MoveTo::create(0.2, cutPos.at(0)),CallFunc::create(endFunc),nullptr));
            auto inner = knife->getChildByName("inner");
            inner->runAction(MoveTo::create(0.2, inner->getContentSize()*.5));
        }
        knife->removeAllComponents();
        knife->setVisible(true);
        
    });
}




void CutFruitLayer::onEnterTransitionDidFinish(){
    BaseStepLayer::onEnterTransitionDidFinish();
    if(cutPaths.size()>0){
        show();
        auto bowl = _operate->getNodeByName("bowl");
        ActionHelper::showBackInOut(bowl,bowl->getPosition(),ActionHelper::ShowDirection::show_from_right,[this](){
            _operate->getNodeByName("bowlShade")->runAction(FadeIn::create(0.2f));
        },0.8f);
        bowl->setVisible(true);
    }
}

void CutFruitLayer::addParicle(const Vec2& v){
    auto paticle = ParticleSystemQuad::create("particles/decorateParticle.plist");
    paticle->setPosition(v);
    paticle->setBlendFunc({GL_ONE_MINUS_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA});
    addChild(paticle,30);
    SoundPlayer::getInstance()->playEffect("sound/general/draw_success.mp3");
}

void CutFruitLayer::cutAllEnd(){
    auto bowlShade = _operate->getNodeByName("bowlShade");
    bowlShade->setVisible(false);
    auto bowl = _operate->getNodeByName("bowl");
    bowl->runAction(Sequence::create(ScaleTo::create(0.9f, 1.25f),CallFunc::create([=](){
        this->addChild(particleLayer::create(),10);
    }),DelayTime::create(1.5),CallFunc::create([](){
          Director::getInstance()->replaceScene(TransitionPageTurn::create(1.2, MakeIce::createScene(), false));
    }), nullptr));
    bowl->runAction(JumpTo::create(0.9f, bowl->getParent()->getContentSize()*.5f, 200, 1));
}